package com.example.musicplayer

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import androidx.core.app.NotificationCompat

class MusicService : Service() {
    companion object {
        const val Command = "Operate"
        const val CHANNEL_ID = "MusicPlayerChannel"
    }

    val TAG = "MusicService"
    val mediaplayer = MediaPlayer()
    val musicList = mutableListOf<String>()          // 音乐文件路径列表
    val musicNameList = mutableListOf<String>()      // 音乐名称列表
    var current = 0                                   // 当前播放的音乐索引
    var isPause = false                               // 音乐是否暂停的状态
    val binder = MusicBinder()

    inner class MusicBinder : Binder() {
        val musicName: String
            get() {
                return if (musicNameList.isNotEmpty() && current in musicNameList.indices) {
                    musicNameList[current]
                } else {
                    "无音乐"  // 如果音乐列表为空，返回默认值
                }
            }

        var currentPosition: Int
            get() = mediaplayer.currentPosition
            set(value) = mediaplayer.seekTo(value)

        val duration: Int
            get() = mediaplayer.duration

        val size: Int
            get() = musicList.size

        val currentIndex: Int
            get() = current
    }

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()  // 创建通知渠道
        getMusicList()  // 初始化获取音乐列表
        mediaplayer.setOnPreparedListener {
            it.start()  // 准备完成后开始播放
        }
        mediaplayer.setOnCompletionListener {
            current++
            if (current >= musicList.size) {
                current = 0  // 循环播放
            }
            play()  // 播放下一首
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val Operate = intent?.getIntExtra(Command, 1) ?: 1
        when (Operate) {
            1 -> play()
            2 -> Pause()
            3 -> Stop()
            4 -> Next()
            5 -> Prev()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    fun Pause() {
        if (isPause) {
            mediaplayer.start()
            isPause = false
        } else {
            mediaplayer.pause()
            isPause = true
        }
    }

    fun Stop() {
        mediaplayer.stop()
        stopSelf()
    }

    fun Next() {
        current++
        if (current >= musicList.size) {
            current = 0
        }
        play()
    }

    fun Prev() {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
        play()
    }

    fun play() {
        if (musicList.isEmpty()) {
            Log.d(TAG, "Music list is empty, cannot play music.")
            return
        }

        val path: String = musicList[current]
        Log.d(TAG, "Attempting to play music at path: $path")

        mediaplayer.reset()
        try {
            mediaplayer.setDataSource(path)
            mediaplayer.setOnPreparedListener {
                Log.d(TAG, "Music prepared, starting playback.")
                it.start()
                updateNotification() // 在这里更新通知
            }
            mediaplayer.prepareAsync()  // 异步准备音乐
        } catch (e: Exception) {
            Log.e(TAG, "Error playing music", e)
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                "Music Player Channel",
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(serviceChannel)
        }
    }

    @SuppressLint("NotificationPermission")
    private fun updateNotification() {
        val notificationIntent = Intent(this, MainActivity::class.java)
        // 添加 FLAG_IMMUTABLE
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // 添加 FLAG_IMMUTABLE
        )

        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Playing")
            .setContentText(musicNameList[current]) // 当前播放的音乐名称
            .setSmallIcon(R.drawable.ic_stat_name) // 确保你有这个图标
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build()

        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.notify(1, notification) // 通知ID为1
    }


    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    @SuppressLint("Range")
    private fun getMusicList() {
        val resolver = contentResolver
        val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TITLE)
        val cursor = resolver.query(uri, projection, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
                if (path != null && name != null) {
                    musicList.add(path)
                    musicNameList.add(name)
                    Log.d(TAG, "Found music: $name at path: $path")
                } else {
                    Log.d(TAG, "Skipped invalid music entry with null path or name")
                }
            }
            cursor.close()
        } else {
            Log.d(TAG, "Cursor is null, no music found.")
        }
    }

}
